package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.common.util.AESUtil;
import com.smarthospital.common.util.JWTUtil;
import com.smarthospital.contants.SHConst;
import com.smarthospital.dao.daoService.UserDaoService;
import com.smarthospital.entity.dto.WxResultJscode2sessionDTO;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.service.LoginService;
import com.smarthospital.service.WxApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * create by sym  2020/8/24 20:44.
 */
@Service
@Slf4j
public class LoginServiceIpml implements LoginService {

    @Autowired
    private WxApiService wxApiService;

    @Autowired
    private UserDaoService userDaoService;

    @Autowired
    private UserServiceImpl userService;


    /**
     *
     * @param source  来源 0_小程序
     * @param code  微信code
     * @return  token
     */
    @Override
    public String login(Integer source, String code) {

        WxResultJscode2sessionDTO wxResultJscode2sessionDTO = wxApiService.jscode2session(source, code);
        String openid = wxResultJscode2sessionDTO.getOpenid();

        User user = userDaoService.selectByoPenId(openid);
        if (null == user) {
            user = userService.initUser(openid);
        }
        String jsonString = JSON.toJSONString(user);
        //jsonString 后再使用对称加密
        jsonString = AESUtil.encrypt(jsonString);
        HashMap<String, String> map = new HashMap<>();
        map.put(SHConst.JWT_PAYLOD_KEY,jsonString);
        return JWTUtil.generateToken(map);
    }

    @Override
    public User checkToken(HttpServletRequest request) {
//        return userDaoService.selectByUnionid("aaa");
        String token = request.getHeader(SHConst.SH_TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new CommonException(CodeMsg.ERROR_LOGIN,"token为空");
        }
        DecodedJWT tokenInfo = null;
        try {
            tokenInfo = JWTUtil.getTokenInfo(token);
        } catch (Exception e) {
            log.error("JWTUtil.getTokenInfo err {}",e.getMessage(),e);
            throw new CommonException(CodeMsg.ERROR_LOGIN,"解析token出错");
        }
        String payload = tokenInfo.getPayload();
        //payload 需要逆base转化
        byte[] bytes = Base64Utils.decodeFromString(payload);
        String payloadStr = new String(bytes);
        //转化后的string 是在生成token时AES加密过的  还需要解密
        Map<String,String> map = JSONObject.parseObject(payloadStr, Map.class);
        //解密
        String Str = map.get(SHConst.JWT_PAYLOD_KEY);
        String jsonStr = AESUtil.decrypt(Str);

        return JSONObject.parseObject(jsonStr,User.class);
    }


}
